//
//  WBOAuthViewController.swift
//  weibo
//
//  Created by wenquan wang on 12/9/16.
//  Copyright © 2016 wenquan wang. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBOAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirectURI)"
        guard let url = URL(string: urlString) else {
            return
        }
        let request = URLRequest(url: url)
        
        webView.loadRequest(request)
    }
    
    override func loadView(){
        webView.delegate = self
        webView.scrollView.isScrollEnabled = false
        view = webView
        view.backgroundColor = UIColor.white
        
        title = "weibo login"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Return", fontSize: 14, target: self, action: #selector(close), isBack: true)
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Auto Fill", target: self, action: #selector(autoFill))
    }
    
    @objc func close(){
        SVProgressHUD.dismiss()
        
        dismiss(animated: true, completion: nil)
    }
    @objc private func autoFill(){
        let js = "document.getElementById('userId').value = '0013108951522'; " +
        "document.getElementById('passwd').value = '{Abcd1234}';"
        
        webView.stringByEvaluatingJavaScript(from: js)
    }
}

extension WBOAuthViewController: UIWebViewDelegate {
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //http://baidu.com/?code=ad5fe5fe9c285a28a0014033396389b8
        //not baidu return
        if request.url?.absoluteString.hasPrefix(WBRedirectURI) == false {
            return true;
        }
        //print("load request---\(request.url?.absoluteString)")
        //print("load request---\(request.url?.query)")
        
        if request.url?.query?.hasPrefix("code=") == false{
            print("cancel auth!")
            close()
            
            return false
        }
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        //print("get auth code: \(code)")
        /**
         tokenRequest(method: .GET, urlString: urlString, parameters: parames as [String : AnyObject]?){
         (json:AnyObject?, isSuccess:Bool) in
         let result = json?["statuses"] as? [[String: AnyObject]]
         
         completion((list: result, isSuccess: isSuccess))
         }
        */
        WBNetworkManager.shared.loadAccessToken(code: code) {
            (isSuccess: Bool) in
            if !isSuccess {
                SVProgressHUD.showInfo(withStatus: "Network request failure!")
            }
            else{
                SVProgressHUD.showInfo(withStatus: "Login Success!")
                
                NotificationCenter.default.post(
                    name: NSNotification.Name(rawValue: WBUserLoginSuccessedNotication),
                    object: nil)
                
                self.close()
            }
        }
        return false;
    }
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}

